package com.gwz.sys.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.gwz.sys.utils.RandomUtils;

@Controller
@RequestMapping("upload")
public class UploadController {
	
	@Value("${erp.upload.path}")
	private String uploadPath;
	
	@RequestMapping("uploadFile")
	@ResponseBody
	public Map<String, Object> uploadFile(MultipartFile mf){
		String oldName = mf.getOriginalFilename();
		String dirName = RandomUtils.createDateStrUseCurrrentDate();
		String newName = RandomUtils.createFileNameUseTime(oldName);
		File dir = new File(uploadPath,dirName);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir,newName);
		Map<String, Object> map = new HashMap<>();
		try {
			mf.transferTo(file);
			map.put("code",200);
		} catch (Exception e) {
			map.put("code",-1);
			e.printStackTrace();
		}
		map.put("path", dirName+"/"+newName);
		return map;
	}
	
	@RequestMapping("showImage")
	public ResponseEntity showImage(String path) {
		// 获得需要下载的文件对象
		File file = new File(uploadPath, path);
		// 将下载的文件，封装byte[]
		byte[] bytes = null;
		try {
			bytes = FileUtils.readFileToByteArray(file);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 创建封装响应头信息的对象
		HttpHeaders header = new HttpHeaders();
		// 封装响应内容类型(APPLICATION_OCTET_STREAM 响应的内容不限定)
		header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		// 设置下载的文件的名称
		header.setContentDispositionFormData("attachment", "123.jpg");
		// 创建ResponseEntity对象
		ResponseEntity entity = new ResponseEntity(bytes, header, HttpStatus.CREATED);
		return entity;
	}
}
